<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>城市温度分析 - 带数据解释</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        body {
            background: #f4f4f4;
            color: #333;
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 20px;
        }
       .filter-container {
            margin: 20px;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: center;
            gap: 20px;
        }
        select {
            padding: 10px 15px;
            border: 1px solid #ccc;
            border-radius: 6px;
            min-width: 220px;
            background: #fff;
            color: #333;
            font-size: 16px;
            font-weight: bold;
        }
        #chart-container {
            width: 90%;
            height: 600px;
            margin: 30px auto;
            border-radius: 8px;
            background: #fff;
            padding: 20px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
        }
       .chart-title {
            text-align: center;
            font-size: 28px;
            margin: 20px 0;
            color: #333;
        }
       .return-home {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px 20px;
            background-color: #555;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            text-decoration: none;
            z-index: 1000;
        }
       .return-home:hover {
            background-color: #333;
        }
       .data-explanation {
            width: 90%;
            margin: 0 auto 30px;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            border-left: 4px solid #555;
        }
       .explanation-title {
            font-size: 18px;
            font-weight: bold;
            color: #555;
            margin-bottom: 10px;
        }
       .explanation-content {
            line-height: 1.6;
            color: #666;
        }
    </style>
</head>
<body>


    <div class="chart-title">城市温度分析</div>

    <div class="filter-container">
        <select id="citySelect">
            {% for city in cities %}
                <option value="{{ city }}" {% if loop.first %}selected{% endif %}>{{ city }}</option>
            {% endfor %}
        </select>

        <select id="yearSelect">
            <option value="">全部年份</option>
            {% for year in years %}
                <option value="{{ year }}">{{ year }}</option>
            {% endfor %}
        </select>

        <select id="tempTypeSelect">
            <option value="max">最高温度</option>
            <option value="min">最低温度</option>
            <option value="both">最高/最低温度</option>
        </select>
    </div>

    <div id="chart-container"></div>

    <!-- 数据解释区域 -->
    <div class="data-explanation" id="dataExplanation">
        <div class="explanation-title">数据说明</div>
        <div class="explanation-content" id="explanationContent">
            请选择城市和年份以查看温度数据及分析
        </div>
    </div>

    <script type="text/javascript">
        const chartDom = document.getElementById('chart-container');
        const myChart = echarts.init(chartDom);
        const explanationContent = document.getElementById('explanationContent');

        // 城市气候特征库（可根据实际数据扩展）
        const CITY_CLIMATE = {
            "北京": "温带季风气候，夏季高温多雨，冬季寒冷干燥，四季分明。",
            "上海": "亚热带季风气候，夏季炎热湿润，冬季温和少雨，春秋较短。",
            "广州": "亚热带季风气候，全年温暖湿润，夏季长而炎热，冬季短暂温和。",
            "哈尔滨": "温带大陆性季风气候，夏季凉爽短促，冬季寒冷漫长，温差较大。",
            "成都": "亚热带季风气候，全年温和湿润，夏季多雨，冬季少雪，多云雾。",
            "_default": "该城市气候特征暂未收录，数据展示为温度变化趋势。"
        };

        // 温度趋势分析函数
        function analyzeTemperature(data, city, year, tempType) {
            if (!data || data.temps.length === 0) {
                return "暂无足够数据进行分析";
            }

            const temps = data.temps;
            const months = data.months.map(m => new Date(m).getMonth() + 1);
            const avgTemp = temps.reduce((sum, val) => sum + val, 0) / temps.length;
            const maxTemp = Math.max(...temps);
            const minTemp = Math.min(...temps);
            const maxMonth = months[temps.indexOf(maxTemp)];
            const minMonth = months[temps.indexOf(minTemp)];

            // 获取城市气候特征
            const climate = CITY_CLIMATE[city] || CITY_CLIMATE["_default"];

            let analysis = `<p><strong>气候特征：</strong>${climate}</p>`;
            analysis += `<p><strong>温度概况：</strong>${tempType === 'max' ? '最高' : tempType === 'min' ? '最低' : '最高和最低'}温度数据显示，${year || '所选时间段'}${city}的月平均${tempType === 'both' ? '气温' : tempType === 'max' ? '最高气温' : '最低气温'}为${avgTemp.toFixed(1)}℃，最高值出现在${maxMonth}月（${maxTemp}℃），最低值出现在${minMonth}月（${minTemp}℃）。</p>`;

            // 趋势分析
            if (year) {
                analysis += `<p><strong>季节趋势：</strong>`;
                if (tempType === 'both') {
                    analysis += `从图表可以看出，${city}${year}年的最高温度和最低温度呈现明显的季节性变化，夏季（6-8月）温度较高，冬季（12-2月）温度较低，符合${CITY_CLIMATE[city] || '该地区'}的气候特征。`;
                } else {
                    analysis += `从图表可以看出，${city}${year}年的${tempType === 'max' ? '最高' : '最低'}温度呈现明显的季节性变化，夏季（6-8月）${tempType === 'max' ? '温度较高' : '温度相对温和'}，冬季（12-2月）${tempType === 'max' ? '温度明显下降' : '温度较低'}，符合${CITY_CLIMATE[city] || '该地区'}的气候特征。`;
                }

                // 异常值检测
                const isAbnormal = (maxTemp - avgTemp) > 5 || (avgTemp - minTemp) > 5;
                if (isAbnormal) {
                    analysis += `与历史平均数据相比，${year}年${maxMonth}月的${maxTemp}℃属于${tempType === 'max' ? '较高值' : '相对较高值'}，可能受${tempType === 'max' ? '极端天气' : '气候异常'}影响。`;
                }
            } else {
                analysis += `<p><strong>长期趋势：</strong>从多年数据来看，${city}的${tempType === 'both' ? '气温' : tempType === 'max' ? '最高气温' : '最低气温'}呈现${tempType === 'max' ? '夏季高温逐渐上升' : tempType === 'min' ? '冬季低温有所缓和' : '季节性温差略微缩小'}的趋势，这可能与全球气候变化有关。</p>`;
            }

            return analysis;
        }

        const baseOption = {
            grid: { left: '3%', right: '4%', bottom: '8%', containLabel: true },
            xAxis: {
                type: 'category',
                axisLine: { lineStyle: { color: '#333', width: 1 } },
                axisLabel: {
                    color: '#333',
                    fontSize: 14,
                    interval: 0,
                    formatter: function (value) {
                        const [year, month] = value.split('-');
                        return `${year}年${month}月`;
                    }
                },
                categoryGap: '10%',
            },
            yAxis: {
                type: 'value',
                axisLine: { lineStyle: { color: '#333', width: 1 } },
                splitLine: { lineStyle: { color: '#eee' } },
                axisLabel: {
                    formatter: '{value}℃',
                    color: '#333',
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(255, 255, 255, 0.95)',
                borderColor: '#ccc',
                borderWidth: 1,
                textStyle: { color: '#333', fontSize: 14 },
                formatter: function (params) {
                    const date = params[0].name;
                    const values = params.map(item => `${item.seriesName}: ${item.value}℃`).join('<br>');
                    return `<strong>${date}</strong><br>${values}`;
                }
            },
            legend: {
                data: ['最高温度', '最低温度'],
                textStyle: { color: '#333' },
                bottom: '2%'
            }
        };

        function reset() {
            myChart.clear();
            myChart.setOption(baseOption);
        }

        function updateChart() {
            reset();

            const city = document.getElementById('citySelect').value;
            const year = document.getElementById('yearSelect').value;
            const tempType = document.getElementById('tempTypeSelect').value;

            if (!city) {
                alert('请选择城市');
                explanationContent.innerHTML = "请选择城市和年份以查看温度数据及分析";
                return;
            }

            const requests = [];

            if (tempType === 'max' || tempType === 'both') {
                requests.push(
                    fetch(`/temperature/monthly_high?city=${encodeURIComponent(city)}${year ? `&year=${year}` : ''}`)
                        .then(response => {
                            if (!response.ok) throw new Error(`最高温度请求失败：${response.status}`);
                            return response.json();
                        })
                );
            }
            if (tempType === 'min' || tempType === 'both') {
                requests.push(
                    fetch(`/temperature/monthly_low?city=${encodeURIComponent(city)}${year ? `&year=${year}` : ''}`)
                        .then(response => {
                            if (!response.ok) throw new Error(`最低温度请求失败：${response.status}`);
                            return response.json();
                        })
                );
            }

            myChart.showLoading({
                text: '数据加载中...',
                color: '#333',
                textColor: '#333',
                maskColor: 'rgba(255, 255, 255, 0.7)',
                fontSize: 16
            });

            Promise.all(requests)
                .then(dataList => {
                    myChart.hideLoading();

                    let highData = null;
                    let lowData = null;

                    if (tempType === 'both') {
                        [highData, lowData] = dataList;
                    } else if (tempType === 'max') {
                        [highData] = dataList;
                    } else if (tempType === 'min') {
                        [lowData] = dataList;
                    }

                    const series = [];
                    let xData = [];

                    if (highData) {
                        xData = highData.months.map(m => {
                            const [yearPart, monthPart] = m.split('-');
                            return `${yearPart}-${monthPart}`;
                        });
                    } else if (lowData) {
                        xData = lowData.months.map(m => {
                            const [yearPart, monthPart] = m.split('-');
                            return `${yearPart}-${monthPart}`;
                        });
                    }

                    if (highData && highData.temps) {
                        series.push({
                            name: '最高温度',
                            type: 'bar',
                            data: highData.temps,
                            barWidth: tempType === 'both' ? '25%' : '40%',
                            itemStyle: { color: '#ff6347' },
                            label: {
                                show: true,
                                position: 'top',
                                color: '#333',
                                fontSize: 12,
                                formatter: '{c}℃'
                            }
                        });
                    }

                    if (lowData && lowData.temps) {
                        series.push({
                            name: '最低温度',
                            type: 'bar',
                            data: lowData.temps,
                            barWidth: tempType === 'both' ? '25%' : '40%',
                            itemStyle: { color: '#6495ed' },
                            label: {
                                show: true,
                                position: 'bottom',
                                color: '#333',
                                fontSize: 12,
                                formatter: '{c}℃'
                            }
                        });
                    }

                    if (xData.length === 0) {
                        throw new Error('没有找到匹配的温度数据');
                    }

                    myChart.setOption({
                        grid: { left: '3%', right: '4%', bottom: '8%', containLabel: true },
                        xAxis: {
                            type: 'category',
                            data: xData,
                            axisLine: { lineStyle: { color: '#333', width: 1 } },
                            axisLabel: {
                                color: '#333',
                                fontSize: 14,
                                interval: 0,
                                formatter: function (value) {
                                    const [year, month] = value.split('-');
                                    return `${year}年${month}月`;
                                }
                            },
                            categoryGap: tempType === 'both' ? '30%' : '10%',
                        },
                        yAxis: {
                            type: 'value',
                            axisLine: { lineStyle: { color: '#333', width: 1 } },
                            splitLine: { lineStyle: { color: '#eee' } },
                            axisLabel: {
                                formatter: '{value}℃',
                                color: '#333',
                                fontSize: 14
                            }
                        },
                        tooltip: {
                            trigger: 'axis',
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#ccc',
                            borderWidth: 1,
                            textStyle: { color: '#333', fontSize: 14 },
                            formatter: function (params) {
                                const date = params[0].name;
                                const values = params.map(item => `${item.seriesName}: ${item.value}℃`).join('<br>');
                                return `<strong>${date}</strong><br>${values}`;
                            }
                        },
                        legend: {
                            data: series.map(s => s.name),
                            textStyle: { color: '#333' },
                            bottom: '2%'
                        },
                        series: series
                    });

                    // 生成数据解释
                    let explanation = `<p><strong>数据说明：</strong>当前展示的是${city}${year ? ` ${year}年` : ''}的${tempType === 'both' ? '最高和最低温度' : tempType === 'max' ? '最高温度' : '最低温度'}数据，单位为摄氏度（℃），数据覆盖${xData.length}个月。</p>`;

                    if (year) {
                        if (tempType === 'both' && highData && lowData) {
                            explanation += analyzeTemperature(highData, city, year, 'max');
                            explanation += analyzeTemperature(lowData, city, year, 'min');
                        } else {
                            const dataToAnalyze = tempType === 'max' ? highData : lowData;
                            explanation += analyzeTemperature(dataToAnalyze, city, year, tempType);
                        }
                    } else {
                        if (tempType === 'both' && highData && lowData) {
                            explanation += analyzeTemperature(highData, city, null, 'max');
                            explanation += analyzeTemperature(lowData, city, null, 'min');
                        } else {
                            const dataToAnalyze = tempType === 'max' ? highData : lowData;
                            explanation += analyzeTemperature(dataToAnalyze, city, null, tempType);
                        }
                    }

                    explanationContent.innerHTML = explanation;

                })
                .catch(error => {
                    myChart.hideLoading();
                    console.error('数据加载错误:', error);
                    alert(`数据加载失败: ${error.message}`);
                    explanationContent.innerHTML = "数据加载失败，请重试";
                });
        }

        document.addEventListener('DOMContentLoaded', () => {
            const defaultCity = document.getElementById('citySelect').options[0].value;
            document.getElementById('yearSelect').value = '';
            updateChart();
        });

        ['citySelect', 'yearSelect', 'tempTypeSelect'].forEach(id => {
            document.getElementById(id).addEventListener('change', updateChart);
        });

        window.addEventListener('resize', () => myChart.resize());
    </script>
</body>
</html>